package com.vizhuo.smscode.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.vizhuo.client.base.AbstractUrls;
import com.vizhuo.client.business.smscode.reply.PostSMSCodeReply;
import com.vizhuo.client.business.smscode.request.PostSMSCodeRequest;

/**
 * 
 */
public class HttpClientUtil {
    private static HttpClient httpClient = null;

    public static void main(String arg[]) throws Exception {
        //String url = "https://10.0.0.185:8443/mobile/smscode/getCode.do";
        String url = "http://10.211.55.3:8080/mobile/smscode/getCode.do";
        // JSONObject params = new JSONObject();
        // params.put("mobile", "18611765343");
        // params.put("TENANT_ID", "123");
        // params.put("NM", "张三");
        // params.put("BRTH_DT", "1983-01-20");
        // params.put("GND_CODE", "1");
        // JSONArray params2 = new JSONArray();
        // JSONObject param3 = new JSONObject();
        // JSONObject param4 = new JSONObject();
        // param3.put("mobile", "18611765343");
        // // param3.put("DOC_NBR", "100200198301202210");
        // // param3.put("DOC_CUST_NM", "test");
        // param4.put("req", param3);
        // params2.add(param4);
        // // params.put("req", params2);
        // String ret = doPost(url).toString();
        // System.out.println(ret);
        Map<String, String> map = Maps.newHashMap();
        map.put("req", "{\"mobile\":\"18600662768\"}");
        String result = sendHttpsRequestByPost(url, map);
        System.out.println(result);
    }

    /**
     * httpClient的get请求方式2
     * 
     * @return
     * @throws Exception
     */
    // public static String doGet(String url, String charset) throws Exception {
    /*
     * 使用 GetMethod 来访问一个 URL 对应的网页,实现步骤: 1:生成一个 HttpClinet 对象并设置相应的参数。 2:生成一个
     * GetMethod 对象并设置响应的参数。 3:用 HttpClinet 生成的对象来执行 GetMethod 生成的Get 方法。
     * 4:处理响应状态码。 5:若响应正常，处理 HTTP 响应内容。 6:释放连接。
     */
    /* 1 生成 HttpClinet 对象并设置参数 */
    // HttpClient httpClient = new HttpClient();
    // // 设置 Http 连接超时为5秒
    // httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    // /* 2 生成 GetMethod 对象并设置参数 */
    // GetMethod getMethod = new GetMethod(url);
    // // 设置 get 请求超时为 5 秒
    // getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
    // // 设置请求重试处理，用的是默认的重试处理：请求三次
    // getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new
    // DefaultHttpMethodRetryHandler());
    // String response = "";
    // /* 3 执行 HTTP GET 请求 */
    // try {
    // int statusCode = httpClient.executeMethod(getMethod);
    // /* 4 判断访问的状态码 */
    // if (statusCode != HttpStatus.SC_OK) {
    // System.err.println("请求出错: " + getMethod.getStatusLine());
    // }
    // /* 5 处理 HTTP 响应内容 */
    // // HTTP响应头部信息，这里简单打印
    // Header[] headers = getMethod.getResponseHeaders();
    // for (Header h : headers)
    // System.out.println(h.getName() + "------------ " + h.getValue());
    // // 读取 HTTP 响应内容，这里简单打印网页内容
    // byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组
    // response = new String(responseBody, charset);
    // System.out.println("----------response:" + response);
    // // 读取为 InputStream，在网页内容数据量大时候推荐使用
    // // InputStream response = getMethod.getResponseBodyAsStream();
    // } catch (HttpException e) {
    // // 发生致命的异常，可能是协议不对或者返回的内容有问题
    // System.out.println("请检查输入的URL!");
    // e.printStackTrace();
    // } catch (IOException e) {
    // // 发生网络异常
    // System.out.println("发生网络异常!");
    // e.printStackTrace();
    // } finally {
    // /* 6 .释放连接 */
    // getMethod.releaseConnection();
    // }
    // return response;
    // }

    /**
     * http post请求
     * 
     * @param url
     * @param json
     * @return
     */

    public static PostSMSCodeReply doPost(String url) {
        // 该方法用于执行http请求，https会报错
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        try {
            Class<PostSMSCodeReply> replyClass = PostSMSCodeReply.class;
            List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
            PostSMSCodeRequest request = new PostSMSCodeRequest();
            request.setMobile("18600662768");
            params.add(new BasicNameValuePair(AbstractUrls.REQUEST_KEY, JSON.toJSONString(request)));
            HttpClient httpClient = getHttpClient();
            HttpPost postMethod = new HttpPost(url);
            postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            // postMethod.addHeader("Cookie", "JSESSIONID=" +
            // UniversalUtil.getInstance().getLoginToken(context));
            HttpResponse response = httpClient.execute(postMethod);
            if (response.getStatusLine().getStatusCode() == 200) {
                String result = EntityUtils.toString(response.getEntity(), "utf-8");
                // Log.i("vizhuo", "response" + "-->" + result);
                return JSON.parseObject(result, replyClass);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * 发送HTTPS POST请求
     * 
     * @param 要访问的HTTPS地址
     *            ,POST访问的参数Map对象 <a href="http://my.oschina.net/u/556800"
     *            class="referer" target="_blank">@return</a> 返回响应值
     * */
    public static final String sendHttpsRequestByPost(String url, Map<String, String> params) {
        String responseContent = null;
        HttpClient httpClient = new DefaultHttpClient();
        // 创建TrustManager
        X509TrustManager xtm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        // 这个好像是HOST验证,此处跳过ssl证书安全验证
        X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }

            public void verify(String arg0, SSLSocket arg1) throws IOException {
            }

            public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {
            }

            public void verify(String arg0, X509Certificate arg1) throws SSLException {
            }
        };
        try {
            // TLS1.0与SSL3.0基本上没有太大的差别，可粗略理解为TLS是SSL的继承者，但它们使用的是相同的SSLContext
            SSLContext ctx = SSLContext.getInstance("TLS");
            // 使用TrustManager来初始化该上下文，TrustManager只是被SSL的Socket所使用
            ctx.init(null, new TrustManager[] { xtm }, null);
            // 创建SSLSocketFactory
            SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
            socketFactory.setHostnameVerifier(hostnameVerifier);
            // 通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
            httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> formParams = new ArrayList<NameValuePair>();
            // 构建POST请求的表单参数
            for (Map.Entry<String, String> entry : params.entrySet()) {
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            // https请求参数
            // List<BasicNameValuePair> params1 = new
            // LinkedList<BasicNameValuePair>();
            // PostSMSCodeRequest request = new PostSMSCodeRequest();
            // request.setMobile("18611765343");
            // params1.add(new BasicNameValuePair(AbstractUrls.REQUEST_KEY,
            // JSON.toJSONString(request)));

            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity(); // 获取响应实体
            if (entity != null) {
                responseContent = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }

    public static synchronized HttpClient getHttpClient() {
        if (httpClient == null) {
            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
            HttpProtocolParams.setUseExpectContinue(params, true);
            int REQUEST_TIMEOUT = 10 * 1000;
            int SO_TIMEOUT = 10 * 1000;
            HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
            ConnManagerParams.setTimeout(params, 1000);

            // 设置访问协议
            SchemeRegistry schreg = new SchemeRegistry();
            schreg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schreg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

            ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schreg);
            httpClient = new DefaultHttpClient(conMgr, params);
        }
        return httpClient;
    }

}
